package com.heatup.apt.common.util.Netty;

import com.google.protobuf.MessageLite;
import io.netty.channel.*;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;

/**
 * 1. 添加 ProtobufVarint32FrameDecoder 用来分割帧
 * 2. 添加 ProtobufEncoder 用来处理消息的编码
 * 3. 添加 ProtobufDecoder 用来处理消息的解码
 * 4. 添加 ObjectHandler 用来处理解码了的消息
 *
 * Created by blank on 2017/11/17 下午4:40
 */
public class ProtoBufInitializer extends ChannelInitializer<Channel> {

    private final MessageLite lite;

    public ProtoBufInitializer(MessageLite lite) {
        this.lite = lite;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new ProtobufVarint32FrameDecoder()); //1
        pipeline.addLast(new ProtobufEncoder()); //2
        pipeline.addLast(new ProtobufDecoder(lite)); //3
        pipeline.addLast(new ObjectHandler()); //4
    }

    public static class ObjectHandler extends SimpleChannelInboundHandler<Object>{
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            // Do something with the object
        }
    }


}
